package cn.com.smart.module.xman.etlMail.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.smart.common.utils.MailConfig;
import cn.com.smart.common.utils.MailUtils;
import cn.com.smart.common.utils.text.Convert;
import cn.com.smart.module.system.user.domain.User;
import cn.com.smart.module.xman.etlMail.domain.Contact;
import cn.com.smart.module.xman.etlMail.domain.EtlMail;
import cn.com.smart.module.xman.etlMail.mapper.ContactMapper;
import cn.com.smart.module.xman.etlMail.mapper.EtlMailMapper;
import cn.com.smart.module.xman.etlMail.service.IEtlMailService;

/**
 * 邮件列 服务层实现
 * 
 * @author xman
 * @date 2019-06-10
 */
@Service
public class EtlMailServiceImpl extends ServiceImpl<EtlMailMapper,EtlMail> implements IEtlMailService 
{
	
	@Value("${smart.profile}")
    private String uploadPath;
	
	@Value("${mail.smtp.host}")
	private String serverHost;
	
	@Value("${mail.smtp.port}")
	private int port;
	
	@Value("${mail.from}")
	private String userName;
	
	@Value("${mail.name}")
	private String displayName;
	
	@Value("${mail.password}")
	private String password;
	
	@Value("${mail.smtp.sslCheckServer}")
	private boolean checkserveridentity;
	
	@Value("${mail.smtp.tlsEnabled}")
	private boolean startTLSEnabled;
	
	@Value("${mail.smtp.sslOnConnect}")
	private boolean sslOnConnect;
	
	@Value("${mail.smtp.charSet}")
	private String charSet;
	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	
	@Autowired
	private ContactMapper contactMapper;

	/**
     * 查询邮件列信息
     * 
     * @param id 邮件列ID
     * @return 邮件列信息
     */
    @Override
	public EtlMail selectById(String id)
	{
	    return baseMapper.selectById(id);
	}
	
	/**
     * 查询邮件列列表
     * 
     * @param etlMail 邮件列信息
     * @return 邮件列集合
     */
	@Override
	public List<EtlMail> selectList(EtlMail etlMail)
	{
	    return baseMapper.selectList(null);
	}
	
    /**
     * 新增邮件列
     * 
     * @param etlMail 邮件列信息
     * @return 结果
     */
	@Override
	public int insert (EtlMail etlMail, List<MultipartFile> files)
	{
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		etlMail.setSender(user.getUserId());
//		sdf.applyPattern("yyyyMMddHHmmss");
//		etlMail.setId("iptv-etl-" + sdf.format(new Date()));
		JSONArray appendix = new JSONArray(files.size());
		if(files.size() > 0) {
			File path = new File(uploadPath + "upload/");
			if(!path.exists()) {
				path.mkdirs();
			}
			files.forEach(f -> {
				String newName = UUID.randomUUID().toString();
				JSONObject json = new JSONObject(3);
				json.put("originalName", f.getOriginalFilename());
				json.put("fileName", newName);
				json.put("size", f.getSize());
				appendix.add(json);
				try {
					f.transferTo(new File(path, newName));
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			});
		}
		etlMail.setAppendix(appendix.toJSONString());
		if(etlMail.getStatus() == 1) {
			List<String> toList = new ArrayList<String>();
			List<String> ccList = new ArrayList<String>();
			if(StringUtils.isNotEmpty(etlMail.getToAddress())) {
				String[] ts = etlMail.getToAddress().split(";", -1);
				for(String to : ts) {
					to = to.trim();
					if(to.length() > 0) {
						toList.add(to);
					}
				}
			}
			if(StringUtils.isNotEmpty(etlMail.getCcAddress())) {
				String[] ts = etlMail.getCcAddress().split(";", -1);
				for(String to : ts) {
					to = to.trim();
					if(to.length() > 0) {
						ccList.add(to);
					}
				}
			}
			//抄送给发件人
			if(StringUtils.isNotEmpty(user.getEmail()) && !ccList.contains(user.getEmail())) {
				ccList.add(user.getEmail());
			}
			List<EmailAttachment> atts = new ArrayList<EmailAttachment>();
			appendix.forEach(f -> {
				JSONObject json = (JSONObject) f;
				EmailAttachment att = new EmailAttachment();
		        att.setPath(uploadPath + "upload/" + json.getString("fileName"));
		        att.setName(json.getString("originalName"));
		        atts.add(att);
			});
			MailConfig config = new MailConfig();
			config.setServerHost(serverHost);
			config.setPort(port);
			config.setUserName(userName);
			config.setDisplayName(displayName);
			config.setPassword(password);
			config.setCheckserveridentity(checkserveridentity);
			config.setStartTLSEnabled(startTLSEnabled);
			config.setSslOnConnect(sslOnConnect);
			config.setCharSet(charSet);
			
//			sdf.applyPattern("yyyy/MM/dd HH:mm:ss");
//			String content = etlMail.getMailBody() + "<br /><br /><b>以下是脚本内容</b><hr/><b>脚本名称：</b>"
//					+ etlMail.getScriptName() + "<br /><b>脚本用途：</b>" + etlMail.getScriptUsage() + "<br /><b>运行时间：</b>"
//					+ sdf.format(new Date(etlMail.getPlanningStartTime() * 1000L)) + " - "
//					+ sdf.format(new Date(etlMail.getPlanningEndTime() * 1000L)) + "<br /><b>脚本：</b><br />"
//					+ etlMail.getScriptContent();
			
			//https://www.cnblogs.com/yuxiaole/p/9332771.html
//			String body = "<span style=\"color:red\"><b>脚本有效期：</b>"
//					+ sdf.format(new Date((etlMail.getPlanningStartTime()==null||etlMail.getPlanningStartTime()==0)?System.currentTimeMillis():(etlMail.getPlanningStartTime() * 1000L))) + " - "
//					+ ((etlMail.getPlanningEndTime()==null||etlMail.getPlanningEndTime()==0)?"永久":sdf.format(new Date(etlMail.getPlanningEndTime() * 1000L))) + "</span><br /><br />"
//					+ etlMail.getMailBody();
			try {
				System.out.println("Send email: " + MailUtils.sendEmail(config, etlMail.getSubject(), etlMail.getMailBody(), toList, ccList, null, atts, user.getUserName(), user.getPhone(), config.getUserName()));
			} catch (EmailException e) {
				e.printStackTrace();
				return 0;
			}
			etlMail.setSendTime((int) (System.currentTimeMillis() / 1000));
			Set<String> emails = new HashSet<String>(toList);
			emails.addAll(ccList);
			Contact contact = new Contact();
			contact.setUserId(etlMail.getSender());
			contactMapper.selectContactList(contact).forEach(c -> {
				if(emails.contains(c.getEmail())) {
					emails.remove(c.getEmail());
				}
			});
			emails.forEach(email -> {
				String name = email.substring(0, email.indexOf('@'));
				Contact c = new Contact();
				c.setName(name);
				c.setEmail(email);
				c.setUserId(etlMail.getSender());
				c.setCreateTime(System.currentTimeMillis() / 1000);
				contactMapper.insertContact(c);
			});
		}
		
	    return baseMapper.insert(etlMail);
	}
	

	/**
     * 删除邮件列对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteBatchIds(String ids)
	{
		return baseMapper.deleteBatchIds(Convert.toListArray(ids));
	}

	
}
